package com.leyou.cart.service;

import com.leyou.cart.domain.Cart;
import com.leyou.common.auth.domain.UserHolder;
import com.leyou.common.constant.LyConstants;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 购物车在redis中的结构
     * Map<hashKey, Map<skuId, Cart>>
     * @param cart
     */
    public void saveCart(Cart cart) {
        //先得到hashKey
        String hashKey = LyConstants.USER_CART_PRE+UserHolder.getId();
        //通过hashKey获取到后面的Map<skuId, Cart>
        BoundHashOperations<String, String, String> redisSkuMap = redisTemplate.boundHashOps(hashKey);
        //得到skuId
        String skuIdKey = cart.getSkuId().toString();
        //判断当前新添加的购物车对象是否在当前购物车中
        Boolean isTrue = redisSkuMap.hasKey(skuIdKey);
        //如果存在
        if(isTrue){
            //把字符串格式的Cart对象转成Cart对象
            Cart redisCart = JsonUtils.toBean(redisSkuMap.get(skuIdKey), Cart.class);
            //修改当前购物车对象中对应skuId的value值中的商品数量
            cart.setNum(cart.getNum()+redisCart.getNum());
        }
        //保存购物车
        redisSkuMap.put(skuIdKey, JsonUtils.toString(cart));

    }

    public List<Cart> findCarts() {
        //获取当前用户的购物车id
        String hashKey = LyConstants.USER_CART_PRE+UserHolder.getId();
        //判断当前用户是否有购物车
        if(!redisTemplate.hasKey(hashKey)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到购物车map,Map<skuId, CartStr>
        BoundHashOperations<String, String, String> cartMap = redisTemplate.boundHashOps(hashKey);
        if(cartMap!=null){
            //得到map的entry对象
            Map<String, String> entries = cartMap.entries();
            //只需要收集entry中的value
            List<Cart> carts = entries.values()
                    .stream()
                    .map(cartStr -> JsonUtils.toBean(cartStr, Cart.class))//把字符串格式的购物车转成对象格式
                    .collect(Collectors.toList());
            return carts;
        }
        throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
    }

    public void saveCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            saveCart(cart);
        }
    }
}
